<!DOCTYPE HTML>
<html  lang="zh" xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8">
<head th:include="include :: header"></head>

<style>
	#ossfile .progress{
		margin-left: 188px;
		width: 200px;
	}
	.content_pic{
		display: inline-block;
		margin-left:20px;
	}
</style>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-packet-addNormal" enctype="multipart/form-data" >

			<div class="form-group">
				<label class="col-sm-3 control-label">模拟用户头像：</label>
				<div class="col-sm-8">
					<input id="userImg" name="userImg" class="form-control" type="hidden">
				</div>
				<div id="ossfile">你的浏览器不支持flash,Silverlight或者HTML5！</div>
				<br/>
				<div id="container">
					<a id="selectfiles" href="javascript:void(0);" class='btn'>选择上传</a>
				</div>
				<pre id="console"></pre>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">红包图片：</label>
				<div class="col-sm-8">
					<input id="redPacketPic" name="redPacketPic" class="form-control" type="hidden" value="">
				</div>
				<div id="ossfile2">你的浏览器不支持flash,Silverlight或者HTML5！</div>
				<br/>
				<div id="container2">
					<a id="selectfiles2" href="javascript:void(0);" class='btn'>选择上传</a>
				</div>
				<pre id="console2"></pre>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">红包金额：</label>
				<div class="col-sm-8">
					<input id="redPacketAdmount" name="redPacketAdmount" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">母红包数量：</label>
				<div class="col-sm-8">
					<input id="number" name="number" class="form-control" type="text">
				</div>
			</div>

			<div class="form-group">	
				<label class="col-sm-3 control-label">子红包数量：</label>
				<div class="col-sm-8">
					<input id="redPacketQuantity" name="redPacketQuantity" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group">	
				<label class="col-sm-3 control-label">广告外部链接：</label>
				<div class="col-sm-8">
					<input id="advertisingExternalLink" name="advertisingExternalLink" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group">	
				<label class="col-sm-3 control-label">广告手机号码：</label>
				<div class="col-sm-8">
					<input id="advertisingPhone" name="advertisingPhone" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group">	
				<label class="col-sm-3 control-label">广告地址：</label>
				<div class="col-sm-8">
					<input id="advertisingAddress" name="advertisingAddress" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">红包描述：</label>
				<div class="col-sm-8">
					<input id="redPacketRemark" name="redPacketRemark" class="form-control" type="text">
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-3 control-label">发红包提示：</label>
				<div class="col-sm-8">
					<p>（红包金额X母红包数量=总金额）（母红包数量*子红包数量=总红包数量）</p>
					<p>（母红包数量是每个人可以领取的红包数量）</p>
				</div>
			</div>

			<div class="form-group">
				<div class="form-control-static col-sm-offset-9">
					<button type="submit" class="btn btn-primary">提交</button>
					<button onclick="$.modal.close()" class="btn btn-danger" type="button">关闭</button>
				</div>
			</div>
		</form>
	</div>
    <div th:include="include::footer"></div>
    <script type="text/javascript">
		//var prefix = ctx + "module/packet";
		var prefix = ctx + "module/packetConfig";
		$("#form-packet-addNormal").validate({
			rules:{
                redPacketAdmount:{
					required:true
				},
                redPacketQuantity:{
                    required:true,
                    digits:true
				},
                redPacketRemark:{
                    required:true
				}
			},
			submitHandler: function(form) {
                var formData = $('#form-packet-addNormal').serialize();
				var number = $("#number").val();
                //var formData = new FormData($('#form-packet-addNormal').get(0));
                console.log(formData);
                $.operate.save(prefix + "/add", formData);
			}
		});
	</script>
	<script th:src="@{/js/plupload-2.1.2/js/plupload.full.min.js}"></script>
	<script>
		$(function () {
            accessid = ''
            accesskey = ''
            host = ''
            policyBase64 = ''
            signature = ''
            callbackbody = ''
            key = ''
            g_object_name = ''
            filename = '';
            ret = false;
            function send_request()
            {
                var xmlhttp = null;
                if (window.XMLHttpRequest)
                {
                    xmlhttp=new XMLHttpRequest();
                }
                else if (window.ActiveXObject)
                {
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }

                if (xmlhttp!=null)
                {
                    serverUrl =  ctx + "file/getUploadToken?"+"fileName="+filename;;
                    xmlhttp.open( "GET", serverUrl, false );
                    xmlhttp.send(null);
                    return xmlhttp.responseText
                }
                else
                {
                    alert("Your browser does not support XMLHTTP.");
                }
            };

            function get_signature()
            {
                body = send_request();
                var obj = eval ("(" + body + ")");
                host = obj['uploadUrl'];
                policyBase64 = obj['policy'];
                accessid = obj['accessKey'];
                signature = obj['signature'];
                expire = parseInt(obj['expire']);
                callbackbody = obj['callback'];
                key = obj['key'];
                return true;
            };


            function set_upload_param(up, filename, ret)
            {

                ret = get_signature()
                g_object_name = key;
                new_multipart_params = {
                    'key' : g_object_name,
                    'policy': policyBase64,
                    'OSSAccessKeyId': accessid,
                    'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
                    'callback' : callbackbody,
                    'signature': signature,
                };

                up.setOption({
                    'url': host,
                    'multipart_params': new_multipart_params
                });

                up.start();
            }

            /*上传用户头像*/
            var uploader_avator = new plupload.Uploader({
                runtimes : 'html5,flash,silverlight,html4',
                browse_button : 'selectfiles',
                //multi_selection: false,
                container: document.getElementById('container'),
                flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
                silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
                url : 'http://oss.aliyuncs.com',
                filters: {
                    mime_types : [ //只允许上传图片和zip,rar文件
                        { title : "Image files", extensions : "jpg,jpeg,gif,png,bmp" },
                        { title : "Zip files", extensions : "zip,rar" }
                    ],
                    max_file_size : '10mb', //最大只能上传10mb的文件
                    prevent_duplicates : true //不允许选取重复文件
                },

                init: {
                    PostInit: function() {
                        document.getElementById('ossfile').innerHTML = '';
                    },
                    FilesAdded: function(up, files) {
                        plupload.each(files, function(file) {
                            document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' +'<b></b>'
                                +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                                +'</div>';
                            filename = file.name;
                            set_upload_param(uploader_avator, filename, false);
                            //console.log(filename);
                        });
                    },

                    BeforeUpload: function(up, file) {
                        set_upload_param(up, file.name, true);
                    },
                    UploadProgress: function(up, file) {
                        var d = document.getElementById(file.id);
                        d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                        var prog = d.getElementsByTagName('div')[0];
                        var progBar = prog.getElementsByTagName('div')[0]
                        progBar.style.width= 2*file.percent+'px';
                        progBar.setAttribute('aria-valuenow', file.percent);
                    },

                    FileUploaded: function(up, file, info) {
                        if (info.status == 200)
                        {
                            var g_object_name_val=host +"/"+ g_object_name;
                            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML =
                                '<img style="width: 200px;height: 150px;" src="' +g_object_name_val+'"/>';
                            $("#userImg").val(g_object_name_val);
                            //ret=false;
                        }
                        else
                        {
                            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                        }
                    },
                    Error: function(up, err) {
                        if (err.code == -600) {
                            document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
                        }
                        else if (err.code == -601) {
                            document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
                        }
                        else if (err.code == -602) {
                            console.log(111111111);
                            document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
                        }
                        else
                        {
                            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
                        }
                    }
                }
            });

            uploader_avator.init();

            /*上传九宫格图片*/
            var uploader_pic = new plupload.Uploader({
                runtimes : 'html5,flash,silverlight,html4',
                browse_button : 'selectfiles2',
                //multi_selection: false,
                container: document.getElementById('container'),
                flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
                silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
                url : 'http://oss.aliyuncs.com',
                filters: {
                    mime_types : [ //只允许上传图片和zip,rar文件
                        { title : "Image files", extensions : "jpg,jpeg,gif,png,bmp" },
                        { title : "Zip files", extensions : "zip,rar" }
                    ],
                    max_file_size : '10mb', //最大只能上传10mb的文件
                    prevent_duplicates : true //不允许选取重复文件
                },

                init: {
                    PostInit: function() {
                        document.getElementById('ossfile2').innerHTML = '';
                    },
                    FilesAdded: function(up, files) {
                        plupload.each(files, function(file) {
                            document.getElementById('ossfile2').innerHTML += '<div class="content_pic" id="' + file.id + '">' +'<b></b>'
                                +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                                +'</div>';
                            filename = file.name;
                            set_upload_param(uploader_pic, filename, false);
                            //console.log(filename);
                        });
                    },

                    BeforeUpload: function(up, file) {
                        set_upload_param(up, file.name, true);
                    },
                    UploadProgress: function(up, file) {
                        var d = document.getElementById(file.id);
                        d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                        var prog = d.getElementsByTagName('div')[0];
                        var progBar = prog.getElementsByTagName('div')[0]
                        progBar.style.width= 2*file.percent+'px';
                        progBar.setAttribute('aria-valuenow', file.percent);
                    },

                    FileUploaded: function(up, file, info) {
                        if (info.status == 200)
                        {
                            var g_object_name_val=host +"/"+ g_object_name;
                            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML =
                                '<img style="width: 200px;height: 150px;" src="' +g_object_name_val+'"/>';
                            redPacketPic_pre=$("#redPacketPic").val();
                            console.log(redPacketPic_pre);
							if(redPacketPic_pre){
								$("#redPacketPic").val(redPacketPic_pre+","+g_object_name_val);
							}else{
								$("#redPacketPic").val(g_object_name_val);
							}
                            //ret=false;
                        }
                        else
                        {
                            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                        }
                    },
                    Error: function(up, err) {
                        if (err.code == -600) {
                            document.getElementById('console2').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
                        }
                        else if (err.code == -601) {
                            document.getElementById('console2').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
                        }
                        else if (err.code == -602) {
                            console.log(22222222);
                            document.getElementById('console2').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
                        }
                        else
                        {
                            document.getElementById('console2').appendChild(document.createTextNode("\nError xml:" + err.response));
                        }
                    }
                }
            });

            uploader_pic.init();
        })


	</script>
</body>
</html>
